import Taro from '@tarojs/taro';

const PAGE_LEVEL_LIMIT = 10;

/**
 * 调用时不用把参数补全; getValue(array, key) 一样可以调用
 * @param array 数组
 * @param key 指定的数值
 * @returns {string|string|string}
 */
export function getConstantValue(array: any[], key: string, strKey?: string, strValue?: string): string {
  let result = '';
  let _strKey = 'id';
  let _strValue = 'value';
  if (strKey) {
    _strKey = strKey;
  }
  if (strValue) {
    _strValue = strValue;
  }
  if (array) {
    for (const item of array) {
      if (key == item[_strKey]) {
        result = item[_strValue];
      }
    }
  }
  return result;
}

/**
 * Guid
 */
export function Guid() {
  function S4() {
    // eslint-disable-next-line no-bitwise
    return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
  }
  return `${S4()}${S4()}-${S4()}-${S4()}-${S4()}-${S4()}${S4()}${S4()}`;
}

/**
 * 跳转页面
 * @param url
 * @param {{}} params
 * @param {{}} options
 */
export function gotoPage(url: string, params: any = {}, options: any = {}) {
  const pages = Taro.getCurrentPages();
  let method = options.method || 'navigateTo';
  if (url && typeof url === 'string') {
    if (method === 'navigateTo' && pages.length >= PAGE_LEVEL_LIMIT - 3) {
      method = 'redirectTo';
    }

    if (method === 'navigateToByForce') {
      method = 'navigateTo';
    }

    if (method === 'navigateTo' && pages.length === PAGE_LEVEL_LIMIT) {
      method = 'redirectTo';
    }

    let extend = '';
    for (const key in params) {
      extend += '&' + key + '=' + params[key];
    }
    if (extend.length) {
      url += '?' + extend.substr(1, extend.length - 1);
    }

    Taro[method]({ url });
  }
}

/**
 * 将一个数组打乱
 *
 * @param arr
 * @returns
 */
export function shuffle(arr: number[]) {
  let i = arr.length;
  while (i) {
    let j = Math.floor(Math.random() * i--);
    [arr[j], arr[i]] = [arr[i], arr[j]];
  }
  return arr;
}
